package top.lenjon.lib.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.lenjon.lib.annotation.MailSign;
import top.lenjon.lib.entity.Book;
import top.lenjon.lib.entity.Log;
import top.lenjon.lib.entity.UserDetail;
import top.lenjon.lib.model.LogModel;
import top.lenjon.lib.model.LoginModel;
import top.lenjon.lib.model.ResponseModel;
import top.lenjon.lib.service.impl.BookServiceImpl;
import top.lenjon.lib.service.impl.LogServiceImpl;
import top.lenjon.lib.service.impl.UserDetailServiceImpl;
import top.lenjon.lib.util.RedisUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wei
 * @since 2020/11/9 17:02
 */
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserDetailServiceImpl userDetailService;

    @Autowired
    private LogServiceImpl logService;

    @Autowired
    private BookServiceImpl bookService;


    @GetMapping("/getMyLog")
    public ResponseModel getMyLog(HttpServletRequest request) {
        LoginModel model = (LoginModel) redisUtil.get(request.getHeader("token"));
        UserDetail user = userDetailService.getUserByUserName(model.getUsername());
        List<Log> logs = logService.getLogByUserId(user.getId());
        List<LogModel> logModels = new ArrayList<>();
        logs.forEach(log -> {
            logModels.add(new LogModel(log,bookService.getById(log.getBookId())));
        });
        return ResponseModel.success("success", logModels);
    }

    @MailSign(value = "续借")
    @GetMapping("/renew")
    public ResponseModel renew(int bookId, HttpServletRequest request) {
        String username = ((LoginModel) redisUtil.get(request.getHeader("token"))).getUsername();
        if (blackListCheck(username)) {
            Book book = bookService.getById(bookId);
            if (bookId == book.getBorrowerId()) {
                logService.renew(bookId);
                return ResponseModel.success("续借成功");
            } else {
                return ResponseModel.error("这不是你的书哟");
            }
        } else {
            return ResponseModel.error("您已进入黑名单，请求失败");
        }
    }


    /**
     * @param username
     * @return 用户是否可用
     */
    private boolean blackListCheck(String username) {
        UserDetail user = userDetailService.getUserByUserName(username);
        return user.getEnabled();
    }
}
